package com.zijin.service.user.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.zijin.PageQureyDTO;
import com.zijin.constant.BusinessContant;
import com.zijin.constant.ErrorMsgConstant;
import com.zijin.dto.user.UserRoleDTO;
import com.zijin.entity.user.Role;
import com.zijin.entity.user.User;
import com.zijin.entity.user.UserRole;
import com.zijin.exception.BaseException;
import com.zijin.mapper.UserRoleMapper;
import com.zijin.result.PageResult;
import com.zijin.service.user.IUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zijin.vo.user.UserRoleVo;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户和角色关联表 服务实现类
 * </p>
 *
 * @author JWei Xu
 * @since 2025-02-01
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Override
    public Boolean addOne(UserRoleDTO dto) {
        dto.setId(null);
        if(ObjectUtil.isNotEmpty(this.lambdaQuery()
                .eq(UserRole::getUserId,dto.getUserId())
                .eq(UserRole::getRoleId,dto.getRoleId())
                .list())){
            throw new BaseException(ErrorMsgConstant.HAVING_ROLE);
        };
        if(!ObjectUtil.isAllNotEmpty(Db.getById(dto.getRoleId(),Role.class),Db.getById(dto.getUserId(), User.class))){
            throw new BaseException(ErrorMsgConstant.DATA_NOT_FOUN);
        }

        UserRole userRole = BeanUtil.copyProperties(dto, UserRole.class);
        return this.save(userRole);
    }

    @Override
    public Boolean delOne(Long id) {
        this.getUserRole(id);
        return this.removeById(id);
    }

    @Override
    public UserRoleVo getUserRole(Long id) {
        UserRoleVo userRole = this.baseMapper.getUserRole(id);
        if(ObjectUtil.isEmpty(userRole)){
            throw new BaseException(ErrorMsgConstant.DATA_NOT_FOUN);
        }
        return userRole;
    }

    @Override
    public PageResult getPage(PageQureyDTO dto) {
        Page<UserRoleVo> page = this.baseMapper.getPage(new Page(dto.getPageNum(), dto.getPageSize()), dto.getSearch());
        return new PageResult(page.getTotal(),page.getRecords());
    }

    @Override
    public void addDefaultRole(Long userId) {
        List<Role> roles = Db.lambdaQuery(Role.class).eq(Role::getRoleKey, BusinessContant.DEFAULT_ROLE).list();
        if(ObjectUtil.isEmpty(roles)){
            throw new BaseException(ErrorMsgConstant.DEFULT_ROLE_NOT_FOUND);
        };
        Long roleId = roles.get(0).getId();
        UserRoleDTO userRoleDTO = UserRoleDTO.builder()
                .userId(userId)
                .roleId(roleId)
                .build();
        this.addOne(userRoleDTO);
    }



}
